define(["dojo/_base/kernel",
        "dojo/_base/declare",
        "dojo/_base/xhr",
        "dojo/dom",
        "dijit/Dialog"], 
		function(dojo,declare,xhr,dom,Dialog) {
	
return declare("Spring.TaskValidator", [Spring.AbstractAsyncValidation],
	{
		taskName: "",
		constructor : function(args) {
			this.originalHandler = null;
			declare.safeMixin(this, args);
		},
		apply : function() {
			var element = dom.byId(this.elementId);
			if (!element) {
				console.error("Could not set up TaskValidator.  Element with id '" + this.elementId + "' not found in the DOM.");
			} else {
				this.originalHandler = element[this.event];
				var context = this;
				element[this.event] = function(event){
					context.handleEvent(event, context);
				};
			}
			return this;
		},
		handleEvent : function(event, context){ 
			var serviceResponse = {available : false, message : "internal error"};
			var xhrCall = dojo.xhrGet;
			if (this.method === 'POST') {
				xhrCall = dojo.xhrPost;
			}
			if (this.method === 'PUT') {
				xhrCall = dojo.xhrPut;
			}
			if (this.method === 'DELETE') {
				xhrCall = dojo.xhrDelete;
			}
			xhrCall({
				sync: true,
		        url: this.url,
		        headers: { "Accept": "application/json" },
		        handleAs: "json",
		        content: {
		            taskName: this.taskName
		        },
		        load: function(response) {
		        	serviceResponse = response;           
		        }.bind(this),
		        error: function() {
		        	console.error("Could not make AJAX service call to url: " + this.url);
		        }.bind(this)
	        });
			if (serviceResponse.available === false) {
				dojo.stopEvent(event);
				this.showInfo(serviceResponse.message);
			} else {
				if(dojo.isFunction(context.originalHandler)) {
					var result = context.originalHandler(event);
					if (result == false) {
						dojo.stopEvent(event);
					}
				}
			}
		},
		showInfo : function(info){
			new Dialog({title: "", content: info}).show();
		}
	});
	
}); 